package niu.toy.spring.mvc.impl.argument;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;

import niu.toy.spring.ioc.annotation.Nullable;
import niu.toy.spring.mvc.HandlerArgumentResolver;
import niu.toy.spring.mvc.HandlerMethodParameter;
import niu.toy.spring.mvc.ModelAndViewContainer;
import niu.toy.spring.mvc.NativeWebRequest;
import niu.toy.spring.mvc.annotation.RequestBody;


import javax.servlet.http.HttpServletRequest;

public class RequestBodyArgumentResolver implements HandlerArgumentResolver {

    @Override
    public boolean supportsParameter(HandlerMethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestBody.class);
    }
    @Override
    @Nullable
    public final Object resolveArgument(HandlerMethodParameter parameter, NativeWebRequest request, ModelAndViewContainer mavContainer) throws Exception {

        String message=IoUtil.readUtf8(((HttpServletRequest)request.getNativeRequest()).getInputStream());
        Object bean= JSONUtil.toBean(message,parameter.getParameterType());
        return bean;
    }


    @Nullable
    protected Object getValueByParameterValues(String name, HandlerMethodParameter parameter, HttpServletRequest request) throws Exception {
        Object arg = null;
        if (arg == null)
        {
            String[] paramValues = request.getParameterValues(name);
            if (paramValues != null) {
                arg = (paramValues.length == 1 ? paramValues[0] : paramValues);
            }
        }
        return arg;
    }
}
